#include <iostream>
#include "nocopy.hpp"
#include "Log.hpp"
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cerrno>
#include <cstring>
#include "commd.hpp"
using namespace std;


void Usage(const string process) {
    cout << "Usage: " << process << "\n\t" << "server_ip server_port\n" << endl;
}

int main(int argc, char* args[]) {
    if (argc != 3) {
        Usage(args[0]);
        return 1;
    }

    string serverip = args[1];
    uint16_t serverport = stoi(args[2]);


    // 客户端就只需要创建套接字即可
    int socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (socketfd < 0) {
        cerr << "socket err:" << strerror(errno) << endl;
        exit(-1);
    }

    cout << "create socket success socketfd is" << socketfd << endl;  

    // 其实客户端也一定要绑定，但是并不需要我们显示的绑定，系统会自动帮我们绑定
    // 客户端会在首次发送数据的时候自动绑定

    // 填充一下server信息
    struct sockaddr_in server;
    bzero(&server, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());


    // 客户端发消息
    while (true) {
        string inbuffer;
        cout << "Please Enter# ";
        getline(cin, inbuffer); // 获取用户输入

        // 将信息发给服务器
        ssize_t n = sendto(socketfd, inbuffer.c_str(), inbuffer.size(), 0, (struct sockaddr*)&server, sizeof server);
        if (n > 0) {
            // 收消息
            char buffer[1024];
            struct sockaddr_in temp;
            socklen_t len = sizeof temp;
            ssize_t m = recvfrom(socketfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&temp , &len);
            if (m > 0) {
                buffer[m] = '\0';
                cout << "server echo# " << buffer << endl;
            } else {
                break;
            }
        } else  {
            break;
        } 
    }

    close(socketfd);
    return 0;
}